package com.library.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WxUntill {
    private static final String APP_ID = "wxe3f54ea3cdf72bd7";
    private static final String SECRET = "a45249c20fe822781142e20d92014588";
    private static final String GRANT_TYPE = "authorization_code";
    public static String getWxOpenid(String code) throws IOException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + SECRET + "&grant_type=" + GRANT_TYPE + "&js_code=" + code;
        //wxVO2 wxVO2 = call(url);
        JSONObject jsonObject = callTO(url);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    public static String getToken() throws IOException {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s&grant_type=%s", APP_ID, SECRET,GRANT_TYPE);
        JSONObject jsonObject = callTO(url);
        String token = jsonObject.getString("access_token");
        return token;
    }
    private static JSONObject callTO(String url) {
        JSONObject token =null;
        try {
            HttpResponse execute = HttpRequest.get(url).execute();
            String responseBody = execute.body();
            token = JSON.parseObject(responseBody);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return token;
    }
    public static String getPhoneNum(String code){
        String phoneNumber = "";
        try {
            // 调用封装的AccessToken类获取access_token
            String access_token = getToken();
            System.out.println("access_token:" + access_token);
            // 准备请求
            // 请求url 拼接上access_token
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
            // 请求参数
            Map<String, String> map = new HashMap<>(1);
            map.put("code", code);
            // 发起请求 注意请求参数map要转成json字符串
            String res = HttpClientInstance.postJson(url, JSON.toJSONString(map), null);
            // 解析请求结果 拿到手机号
            JSONObject jsonObject = JSONObject.parseObject(res);
            System.out.println(jsonObject);
            String phone_info = jsonObject.get("phone_info").toString();
            JSONObject jsonPhone_info = JSONObject.parseObject(phone_info);
            phoneNumber = jsonPhone_info.get("phoneNumber").toString();
        } catch (IOException e) {
            return null;
        } catch (RuntimeException e){
            return null;
        }

        return phoneNumber;
    }
}
